package org.ciallo.simplemusicplayer.activity;

import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.appbar.MaterialToolbar;
import org.ciallo.simplemusicplayer.R;
import org.ciallo.simplemusicplayer.adapter.SongAdapter;
import org.ciallo.simplemusicplayer.data.model.Song;
import org.ciallo.simplemusicplayer.dialog.SongOptionsDialogFragment;
import org.ciallo.simplemusicplayer.viewmodel.SearchViewModel;
import org.ciallo.simplemusicplayer.viewmodel.SharedViewModel;
import timber.log.Timber;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * @author Jukomu
 * @Description: 显示搜索结果的 Activity
 * @Package: org.ciallo.simplemusicplayer.data.model
 * @Project: SimpleMusicPlayer
 * @name: PlaylistSongCrossRef
 * @Date: 2025/5/30-00:58
 * @Filename: PlaylistSongCrossRef
 */
public class SearchActivity extends AppCompatActivity {

    public static final String EXTRA_SEARCH_QUERY = "extra_search_query";

    private MaterialToolbar toolbar;
    private EditText etSearchQuery;
    private RecyclerView recyclerViewResults;
    private SongAdapter songAdapter; // 先只显示歌曲结果
    private TextView tvEmptyResults;
    private ProgressBar progressBarLoading;

    private SearchViewModel searchViewModel;
    private SharedViewModel sharedViewModel; // 用于播放歌曲

    private Timer debounceTimer; // 用于输入防抖，实现延迟搜索
    private final long DEBOUNCE_DELAY_MS = 500; // 500毫秒延迟

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);

        toolbar = findViewById(R.id.toolbar_search_activity);
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayShowTitleEnabled(false); // Toolbar 不显示标题，由EditText作为搜索框
        }

        etSearchQuery = findViewById(R.id.editText_search_query_activity);
        recyclerViewResults = findViewById(R.id.recyclerView_search_results);
        tvEmptyResults = findViewById(R.id.textView_search_empty_results);
        progressBarLoading = findViewById(R.id.progressBar_search_loading);

        // 初始化 ViewModel
        searchViewModel = new ViewModelProvider(this).get(SearchViewModel.class);
        sharedViewModel = new ViewModelProvider(this).get(SharedViewModel.class);

        setupRecyclerView();
        setupSearchInput();
        observeViewModel();

        // 获取从 MainActivity 传递过来的初始查询词 (如果有)
        String initialQuery = getIntent().getStringExtra(EXTRA_SEARCH_QUERY);
        if (initialQuery != null && !initialQuery.isEmpty()) {
            etSearchQuery.setText(initialQuery);
            etSearchQuery.setSelection(initialQuery.length()); // 光标移到末尾
            performSearch(initialQuery); // 立即执行一次搜索
        } else {
            etSearchQuery.requestFocus(); // 自动获取焦点并弹出软键盘
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            if (imm != null) {
                imm.showSoftInput(etSearchQuery, InputMethodManager.SHOW_IMPLICIT);
            }
        }
    }

    private void setupRecyclerView() {
        songAdapter = new SongAdapter(
                (song, position) -> { // OnSongClickListener
                    List<Song> currentList = songAdapter.getCurrentList();
                    if (sharedViewModel != null && currentList != null && !currentList.isEmpty()) {
                        sharedViewModel.playSongAtIndex(new ArrayList<>(currentList), position);
                        // 可以选择在点击后关闭搜索界面或保持
                        // finish();
                    }
                },
                (song, anchorView) -> { // OnSongOptionsClickListener
                    if (getSupportFragmentManager() != null && song != null) {
                        SongOptionsDialogFragment.newInstance(song.getId())
                                .show(getSupportFragmentManager(), SongOptionsDialogFragment.TAG);
                    }
                }
        );
        recyclerViewResults.setLayoutManager(new LinearLayoutManager(this));
        recyclerViewResults.setAdapter(songAdapter);
    }

    private void setupSearchInput() {
        etSearchQuery.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                performSearch(etSearchQuery.getText().toString());
                hideKeyboard();
                return true;
            }
            return false;
        });

        etSearchQuery.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // 取消上一次的延迟任务 (如果有)
                if (debounceTimer != null) {
                    debounceTimer.cancel();
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                // 创建新的延迟任务
                debounceTimer = new Timer();
                debounceTimer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        runOnUiThread(() -> performSearch(s.toString()));
                    }
                }, DEBOUNCE_DELAY_MS);
            }
        });
    }

    /**
     * 执行搜索操作。
     * @param query 查询关键词。
     */
    private void performSearch(String query) {
        Timber.d("Performing search for query: %s", query);
        searchViewModel.setSearchQuery(query);
    }

    private void observeViewModel() {
        searchViewModel.isLoading.observe(this, isLoading -> {
            progressBarLoading.setVisibility(isLoading ? View.VISIBLE : View.GONE);
            if (isLoading) {
                recyclerViewResults.setVisibility(View.GONE);
                tvEmptyResults.setVisibility(View.GONE);
            }
        });

        searchViewModel.songResults.observe(this, songs -> {
            Boolean loading = searchViewModel.isLoading.getValue();
            if (loading != null && loading) {
                return; // 如果仍在加载，则不更新列表，避免闪烁
            }

            if (songs != null && !songs.isEmpty()) {
                songAdapter.submitList(new ArrayList<>(songs));
                recyclerViewResults.setVisibility(View.VISIBLE);
                tvEmptyResults.setVisibility(View.GONE);
            } else {
                songAdapter.submitList(new ArrayList<>());
                recyclerViewResults.setVisibility(View.GONE);
                // 只有在非加载状态且查询词不为空时，才显示“无结果”
                String currentQuery = etSearchQuery.getText().toString().trim();
                if (!currentQuery.isEmpty()) {
                    tvEmptyResults.setText("没有找到与“" + currentQuery + "”相关的歌曲");
                    tvEmptyResults.setVisibility(View.VISIBLE);
                } else {
                    tvEmptyResults.setVisibility(View.GONE); // 如果查询为空，不显示“无结果”
                }
            }
        });

        // 后续可以观察 artistResults, albumResults
    }

    private void hideKeyboard() {
        View view = this.getCurrentFocus();
        if (view != null) {
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            if (imm != null) {
                imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
            }
        }
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            onBackPressed();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onDestroy() {
        // 取消任何活动的 debounceTimer
        if (debounceTimer != null) {
            debounceTimer.cancel();
            debounceTimer = null;
        }
        super.onDestroy();
    }
}
